<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          :value="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="queryEmployee"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @current-change="selectNode"
        />
      </div>

      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>

          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>

          <el-button size="mini" @click="exportEmployee">excel导出</el-button>

        </el-row>

        <!-- 表格组件 -->
        <el-table :data="tableList">
          <el-table-column align="center" label="头像">
            <template #default="{row}">
              <img v-if="row.staffPhoto" :src="row.staffPhoto" alt="" class="username">
              <div v-else class="username">{{ row.username.split('')[0] }}</div>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="goEmployeeDetail(row.id)">查看</el-button>

              <el-button size="mini" type="text">角色</el-button>

              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="delEmployee(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>

            </template>

          </el-table-column>

        </el-table>

        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            @current-change="changeSize"
          />
        </el-row>
      </div>

    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @updateSuccess="getEmployeeList" />
  </div>

</template>

<script>
import { getDepaetmentListAPI } from '@/api/department'
import { delEmployeeAPI, exportEmployeeAPI, getEmployeeListAPI } from '@/api/employee'
import { translateListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },

  data() {
    return {
      showExcelDialog: false,
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      tableList: [],
      total: 0,
      timeId: -1
    }
  },
  created() {
    this.getDepartment()
    this.getEmployeeList()
  },
  methods: {
    async getDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      this.depts = translateListToTreeData(await getDepaetmentListAPI(), 0)
      // 设置选中节点为第一项
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
    },
    // 选中的节点改变
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeListAPI(this.queryParams)
      this.tableList = res.rows
      this.total = res.total
    },
    // 页数改变
    changeSize(value) {
      this.queryParams.page = value
      this.getEmployeeList()
    },
    // 查询员工
    queryEmployee(value) {
      this.queryParams.keyword = value
      // 手写防抖
      clearTimeout(this.timeId)
      this.timeId = setTimeout(() => {
        this.getEmployeeList()
      }, 500)
    },
    // 表格导出
    async exportEmployee() {
      const loading = this.$loading({
        lock: true,
        text: '正在导出中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const res = await exportEmployeeAPI()
      FileSaver.saveAs(res, '员工信息表.xlsx')
      loading.close()
    },
    // 删除员工
    async delEmployee(id) {
      await delEmployeeAPI(id)
      // 当列表数据长度等于1并且页嘛大于1时，让参数页码减一再发送请求
      if (this.list.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    // 查看员工详情
    goEmployeeDetail(id) {
      this.$router.push(`/employee/detail?id=${id}`)
    }
  }
}
</script>

<style lang="scss" scoped>
    .app-container {
    background: #fff;
    display: flex;
    .left {
      width: 280px;
      padding: 20px;
      border-right: 1px solid #eaeef4;
    }
    .right {
      flex: 1;
      padding: 20px;
      .opeate-tools {
        margin:10px ;
      }
      .username {
        height: 30px;
        width: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #04C9BE;
        font-size: 12px;
        display:inline-block;
      }
    }
  }

</style>
